<template>
  <div class="echarts" ref="chartRef"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { getcateBarData } from '@/api/homeData'
import { onMounted, onUnmounted, ref } from "vue";

//图表最终数据

const data = ref(null)

//得到data里的前7个数据
const rdata = {
  cate: [],
  value: []
}

//data前7个数据
const getRdata = () => {
  rdata.cate = data.value.cate.slice(0,7);
  rdata.value = data.value.value.slice(0,7).map(v => Number(v));
}


const chartRef = ref(null);
let myChart = null;

const initChart = () => {
  const option = {
    xAxis: {
      data: rdata.cate,
      axisLabel: {
        interval: 0,
        rotate: 15,
        fontSize: 12,
      },
      axisTick: {
        alignWithLabel: true
      },
      // boundaryGap: false,  
    },
    yAxis: {
      show: true,
      type: "value",
      name: "数量",
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#ccc',
          opacity: 0.5
        }
      },
    },
    grid: {
      top: 10,    // 增加顶部空间
      bottom: 30,  // 增加底部空间，为倾斜的文字留出位置
      left: 70,    // 增加左侧空间，为y轴标签留出位置
      right: 20
    },
    series: [
      {
        data: rdata.value,
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
            0, 0, 0, 1, [{
              offset: 0,
              color: '#63f7cf'
            },
            {
              offset: 1,
              color: '#54e5fc'
            }
          ]
          ),
          borderRadius: [8, 8, 0, 0]
        },
        barWidth: '40%'
      }
    ],
  };

  myChart = echarts.init(chartRef.value); // 初始化 ECharts

  myChart.setOption(option);
};


onMounted(async () => {
  const result = await getcateBarData();
  data.value = result.data;
  data.value.value = data.value.value.map(v => Number(v));
  getRdata();
  initChart();

  setInterval(() => {
    updateData();
  }, 4000)
});


// 记录当前显示的最后一个元素在data中的索引
let currentIndex = 6;

function updateData() {
  // 移除rdata的第一项
  rdata.cate.shift();
  rdata.value.shift();

  // 更新currentIndex，如果到达data的末尾则重置为0
  currentIndex = (currentIndex + 1) % data.value.cate.length;

  // 添加data中的下一项到rdata末尾
  rdata.cate.push(data.value.cate[currentIndex]);
  rdata.value.push(data.value.value[currentIndex]);

  // 更新图表
  myChart.setOption({
    xAxis: {
      data: rdata.cate
    },
    series: [
      {
        data: rdata.value
      }
    ]
  });
}

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});
</script>

<style scoped>
.echarts {
  width: 100%;
  height: 100%;
  min-height: 18vw;
}
</style>
